<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>重置密码</span>
    </div>
    <!-- 表单 -->
    <el-form :model="pwdForm" :rules="pwdFormRules" ref="pwdFormRef" label-width="100px">
      <el-form-item label="原密码" prop="old_pwd">
        <el-input v-model="pwdForm.old_pwd" type="password"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="new_pwd">
        <el-input v-model="pwdForm.new_pwd" type="password"></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="re_pwd">
        <el-input v-model="pwdForm.re_pwd" type="password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updatedPwd">修改密码</el-button>
        <el-button  @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
export default {
  name: 'UserPwd',
  
  data(){
    //自定义验证规则
    //  验证  原密码 与 新密码  是否相同
    const samePwd = (rule, value, callback) => {
    if (value === this.pwdForm. old_pwd) {
      return callback(new Error('新密码不能与旧密码一致'));
     }else{
      callback()
     }
    }
    // 验证  新密码 与 确认密码  是否一致
     const rePwd = (rule, value, callback) => {
    if (value === this.pwdForm.  new_pwd) {
      return callback();
     }else{
      callback(new Error('确认密码与新密码不一致'))
     }
    }
    return {
      // 表单的数据对象
      pwdForm: {
        old_pwd: '',
        new_pwd: '',
        re_pwd: ''
      },
      // 表单的验证规则对象
      pwdFormRules: {
        old_pwd:[
          { required: true, message: '请输入原密码', trigger: 'blur' },
          {pattern:/^\S{6,15}$/,message:'请输入长度是6~16的非空字符串', trigger: 'blur'}
        ],
        new_pwd:[
          { required: true, message: '请输入新密码', trigger: 'blur' },
          {pattern:/^\S{6,15}$/,message:'请输入长度是6~16的非空字符串', trigger: 'blur'},
          //调用函数  原密码 与 新密码  是否相同
          { validator:samePwd, trigger: 'blur'}
        ],
        re_pwd:[
          { required: true, message: '请输入确认新密码', trigger: 'blur' },
          {pattern:/^\S{6,15}$/,message:'请输入长度是6~16的非空字符串', trigger: 'blur'},
          //调用函数  验证  新密码 与 确认密码  是否一致
          { validator:rePwd, trigger: 'blur'}
        ]
      }
    }
  },
  methods:{
    //重置表单
    resetForm() {
      //resetFields() 重置表单的数据和表单的验证规则
      this.$refs.pwdFormRef.resetFields();
    },
    //修改密码
    updatedPwd(){
      //兜底校验
      this.$refs.pwdFormRef.validate(async (valid) => {
        if(!valid)  return  //校验失败
        //发送请求,修改数据
        const {data:res}  = await this.$axios.patch('/my/updatepwd',this.pwdForm)
        if(res.code !==0)return  this.$message.error('密码输入错误')
        //修改成功提示
        this.$message.success('更新密码成功')
        //清空表单
        //resetFields() 重置表单的数据和表单的验证规则
        this.resetFields();
       
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 500px;
}
</style>